/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

import { reject } from "lodash";

/** Promise 的三种状态 */
const PENDING = 'pending' // 
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (error) {
      this.reject(error);
    }
  }

  // Promise 的初始状态
  status = PENDING;

  // 成功的返回值
  value;

  // 失败的原因
  reason;

  // 成功的回调
  successCallBacks = [];

  // 失败的回调
  failCallBacks = [];

  resolve = value => {
    // 如果状态不为 等待 则阻止继续执行
    if (this.status !== PENDING) return;

    // 更改状态
    this.status = FULFILLED;
    this.value = value;
    while (this.successCallBacks.length) this.successCallBacks.shift()();
  }

  reject = reason => {
    if (this.status !== PENDING) return;

    this.status = REJECTED;
    this.reason = reason;
    while (this.failCallBacks.length) this.failCallBacks.shift()();
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason };
    let promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            resolevPromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error)
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolevPromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error)
          }
        }, 0);
      } else {
        this.successCallBacks.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolevPromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            }
          }, 0);
        });
        this.failCallBacks.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolevPromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            }
          }, 0);
        });
      }
    })
    
    return promise2;
  }

  /**
   * 不管是成功还是回调失败以后都要调用 调用以后还可以使用 then 方法 拿到最后的值
   * @param {*} callback 
   * @returns 
   */
  finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);
    }, reason => {
      return MyPromise.resolve(callback).then(() => { throw reason })
    })
  }

  catch (failCallback) {
    return this.then(undefined, failCallback)
  }

  /**
   * 
   * @param {可以是 Promise 对象 也可以是其他值} array 
   * @returns 
   */
  static all (array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        index++;
        // 如果返回总长度等于 数组长度 执行 resolve
        if(index === array.length) resolve(result);
      }
      for (let i = 0; i < array.length; i++) {
        const current = array[i];
        // 如果是 Promise 对象 等待 promise 执行完成以后回调 
        if(current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason));
        } 
        // 如果是其他值 直接添加 
        else {
          addData(i, current);
        }
      }
    })
  }
  
  // 如果是普通值 包装成 Promise 返回 如果是 Promise 直接返回
  static resolve (value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value));
  }
}

/**
* 判断 x 和 promise2 是否相等 阻止循环调用
* 判断 x 是否为 Promise 对象 如果是 则调用 x 执行结果 如果不是直接返回 x
*/
function resolevPromise (promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for Mypromise # <MyPromise>'))
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else{
    resolve(x)
  }
}

export default MyPromise;
